import sys
import re

	
if len(sys.argv)<2:
     print("usage:")
     exit(0)

myfile = open(sys.argv[1], "r")
bytes=[]
ll=[]
l=[]
for line in (myfile):
	if len(line)==0:
		continue
	if line.startswith('#'):
		continue
	if line.startswith('\t\t'):
		c=2				
	elif line.startswith('\t'):
		c=1
	else:
		c=0
			
	s=line.strip(' \t\n')
	s1=s.split('\t')	
	if c==0:
		fmt=''
		syntax=[]

		n=len(s1)
		i=0
		bytes=[]
		while i<n:
			if s1[i][0].isdigit():
				break
			bytes=bytes+s1[i].split(' ')
			i=i+1
		if i<n:
			fmt=s1[i]
			if n>i+1:
				syntax=[s1[i+1]]

		l=[bytes,fmt,syntax]
		ll.append(l)
	elif c==2:
		l[2].append(s1[0])	
	else:
		n=len(s1)	
		fmt=s1[0]
		if n>1:
			syntax=[s1[1]]
		else:
			syntax=[]

		l=[bytes,fmt,syntax]
		ll.append(l)		

print('''
#ifndef dalvik_fmt_h
#define dalvik_fmt_h

#include "types.h"
''')

print('typedef enum _dalvik_fmt{')

for x in ll:
	print('fmt_%s,'%(x[1]))

print('''fmt_max
} DALVIK_FMT;\n''')

for x in ll:
	print('typedef struct _insn_infmt_%s { '%(x[1]))
	last=''	
	for b in x[0]:
		b1=b.split('|')
		if len(b1)==1:
			if last==b+'lo':
				print('uint16_t %smilo;'%(b))
			elif last==b:
				print('uint16_t %smihi;'%(b))					
			else:
				if b=='N/A':
					bb='resved'
				else:
					bb=b
				print('uint16_t %s;'%(bb))
			last=b
		else:
			last=''
			for bb in reversed(b1):
				width=len(bb)*4
				if bb=='??':
					bb='any'
				print('uint16_t %s:%d;'%(bb,width))			
	print('} INSN_INFMT_%s;\n'%(x[1]))	

print('''

typedef struct _ins_info{
 DALVIK_FMT fmt;
 int length;
 int ip;
 unsigned short * code;
} INSN_INFO,*PINSN_INFO;

extern unsigned insn_len_of_fmt[]; 
   

void print_fmt(PINSN_INFO p_insn);
unsigned insn_len_by_fmt(DALVIK_FMT fmt){return fmt<fmt_max?insn_len_of_fmt[fmt]:0;}

#endif// dalvik_fmt_h''')
